package com.sdp.th.cwt;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.actor.SysActorConfig;
import com.sdp.core.bizc.vo.Result;
import com.sdp.th.utils.Utils;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/CWTingController")
public class CWTingController {
	
	@Autowired
	private SysActorConfig sysActorConfig;
	
	private String ACTOR_FIX = "CWT";

	@RequestMapping(value="smoked")
	public Result<?> queryAlarmCount(@RequestBody JSONObject data) {
		log.info("获得烟感原始报文数据:{}",data);
		
		try {
			if(data==null) {
				return Result.error();
			}
			String deviceNo = data.getString("deviceId");
			
			if(StringUtils.isEmpty(deviceNo)) {
				return Result.error();
			}
			
			//传过来的是ID，默认是在编码前面加了99013914
			deviceNo = deviceNo.replace("99013914", "");
			
			String originalMessage = "";
			
			JSONObject payload = data.getJSONObject("payload");
			if(payload!=null && !StringUtils.isEmpty(payload.getString("msg"))) {
				originalMessage = payload.getString("msg");
			}
			
			JSONObject obj = new JSONObject();
			obj.put("deviceNo", deviceNo);
			obj.put("originalMessage", originalMessage);
			if(!StringUtils.isEmpty(data.getString("timestamp"))) {
				obj.put("timestamp", data.getLong("timestamp"));
			}else {
				obj.put("timestamp", System.currentTimeMillis());
			}
			obj.put("data", data);
			
			Map<String,ActorRef> sysActorMap = sysActorConfig.getSysActorMap();
			ActorSystem actorSystem = sysActorConfig.getSysActorSystem();
			String key = ACTOR_FIX+deviceNo;
			ActorRef actor = sysActorMap.get(key);
			if(actor==null) {
				actor = actorSystem.actorOf(Props.create(CWTActor.class), key);
				sysActorMap.put(key, actor);
			}
			actor.tell(obj, ActorRef.noSender());
		} catch (Exception e) {
			log.error("CWTingController执行出现异常：{}",Utils.stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
		}
		return Result.ok();
	} 
	
	
	
}
